package com.atguigu.vodservice.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.common.R;
import com.atguigu.common.exception.GuliException;
import com.atguigu.vodservice.service.VodService;
import com.atguigu.vodservice.utils.ConstantPropertiesUtil;
import com.atguigu.vodservice.utils.InitVodObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
//@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    //上传视频
    @PostMapping("uploadVideoAliyun")
    public R uploadVideoAliyun(MultipartFile file) {
        String videoId = vodService.uploadVideoAli(file);
        return R.ok().data("videoId",videoId);
    }

    //删除一个视频
    @DeleteMapping("{videoId}")
    public R deleteVideoAliyun(@PathVariable String videoId) {
        System.out.println("service-video方法执行了....");
        //模拟超时
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        vodService.removeVideoAliyun(videoId);
        return R.ok();
    }

    //删除多个视频
    //传递多个视频id 使用list集合
    @DeleteMapping("delete-batch")
    public R deleteBatchVideoIds(@RequestParam("videoIdsList") List videoIdsList) {
        vodService.removeBatchVideoIds(videoIdsList);
        return R.ok();
    }

    //根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
            DefaultAcsClient client = InitVodObject.initVodClient(ConstantPropertiesUtil.ACCESS_KEY_ID,ConstantPropertiesUtil.ACCESS_KEY_SECRET);

            //2 创建获取视频凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();

            //3 向request设置视频id
            request.setVideoId(id);

            //4 调用初始化对象里面的方法
            response = client.getAcsResponse(request);

            //5 通过response得到调用返回结果
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);

        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001,"获取视频凭证失败");
        }
    }
}
